import 'dart:ffi';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_2b_client/apis/AuthrizationApi.dart';
import 'package:flutter_2b_client/apis/EmployeeApi.dart';
import 'package:flutter_2b_client/components/LoadingButton.dart';
import 'package:flutter_2b_client/store/EmployeeAuthorizationStore.dart';
import 'package:flutter_2b_client/utils/ToastUtils.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:retrofit/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';

var passwordValidator = (String? value) {
  if (value == null || value.isEmpty) {
    return "请输入密码";
  }
  if (value.length > MAX_PASSWORD_LENGTH ||
      value.length < MIN_PASSWORD_LENGTH) {
    return "密码必须在$MIN_PASSWORD_LENGTH位到$MAX_PASSWORD_LENGTH位之间";
  }
  return null;
};

class LogInPage extends HookWidget {
  static String path = "/logIn";

  LogInPage({Key? key}) : super(key: key);

  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    var phoneNumberState = useState("");
    var passwordState = useState("");
    var showPasswordState = useState(false);
    var enterpriseCodeState = useState("");

    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Padding(
        padding: const EdgeInsets.only(left: 16, right: 16, top: 200),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              Padding(
                padding: const EdgeInsets.only(top: 56),
                child: TextFormField(
                  validator: (value){
                    if (value == null || value.isEmpty) {
                      return "请输入企业代码";
                    }
                  },
                  onChanged: (value) {
                    enterpriseCodeState.value = value;
                  },
                  decoration: const InputDecoration(
                      border: OutlineInputBorder(), label: Text("企业代码")),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 8),
                child: TextFormField(
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return "请输入手机号";
                    }
                    if (value.length != 11) {
                      return "是否输入了正确的手机号";
                    }
                    return null;
                  },
                  onChanged: (value) {
                    phoneNumberState.value = value;
                  },
                  decoration: const InputDecoration(
                      border: OutlineInputBorder(), label: Text("手机号")),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 8),
                child: TextFormField(
                  validator: passwordValidator,
                  onChanged: (value) {
                    passwordState.value = value;
                  },
                  decoration: InputDecoration(
                    border: const OutlineInputBorder(),
                    label: const Text("密码"),
                    suffixIcon: InkWell(
                      child: showPasswordState.value
                          ? Icon(
                              Icons.remove_red_eye,
                              color: Theme.of(context).colorScheme.primary,
                            )
                          : const Icon(Icons.remove_red_eye_outlined),
                      onTap: () {
                        showPasswordState.value = !showPasswordState.value;
                      },
                    ),
                  ),
                  obscureText: !showPasswordState.value,
                ),
              ),
              SizedBox(
                width: double.infinity,
                child: LoadingButton(
                  onPressed: () async {
                    if (_formKey.currentState!.validate()) {
                      HttpResponse<void> response;
                      try {
                        response = await authorizationApi.logIn(
                                                  phoneNumberState.value, passwordState.value,enterpriseCodeState.value);
                      } on DioException catch(e){
                        var statusCode = e.response?.statusCode;
                        if(statusCode==404){
                          if(context.mounted) {
                            showErrorToast(context, "企业代码、手机号或密码错误");
                          }
                        }
                        return;
                      }
                      var header = response
                          .response.headers[HttpHeaders.authorizationHeader];
                      if (header != null) {
                        (await SharedPreferences.getInstance()).setString(
                            HttpHeaders.authorizationHeader, header.first);
                        if (context.mounted) {
                          employeeApi.getMe().then((value) {
                            Provider.of<EmployeeAuthorizationStore>(context,
                                    listen: false)
                                .setMe(value);
                            context.go("/");
                          });
                        }
                      }
                    }
                  },
                  child: const Text("登录"),
                ),
              ),
            ]
                .map((e) => Padding(
                      padding: const EdgeInsets.symmetric(vertical: 4),
                      child: e,
                    ))
                .toList(),
          ),
        ),
      ),
    );
  }
}
